package pl.edu.uj.tcs.blef.protocol;

import java.io.PrintWriter;
import java.net.Socket;

import pl.edu.uj.tcs.blef.server.Table;

public class SetNewDealRequestHandler extends AbstractTableHandler {

	public SetNewDealRequestHandler(Table table) {
		super(table);
	}

	@Override
	public void handle(Request request, Socket socket) {
		System.out.println("Handling " + request.message + " request from " + socket.getInetAddress().getHostAddress());
		SetNewDealRequest ctr = (SetNewDealRequest)request;
		if(!table.isOperator(socket)) {
			System.out.println("Unauthorized operator request from socket: " + socket.getInetAddress().getHostAddress());
			try {
				Request r = new UnknownRequestErrorFactory().build(null, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
			} catch (Exception e){}
		} else {
			if(this.table.getGame() == null){
				try {
					Request r = new UnknownRequestErrorFactory().build(null, new NullRequestHandler());
					r.send(new PrintWriter(socket.getOutputStream()));
				} catch (Exception e){}
			} else {
				try {
					String[] param = new String[1]; param[0] = "OK New deal";
					Request r = new OKRequestFactory().build(param, new NullRequestHandler());
					r.send(new PrintWriter(socket.getOutputStream()));
					table.setNewDeal();
				} catch (Exception e){}
			}
		}
	}

}
